package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.constants.RedisConstants;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.enity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.leyou.common.constants.MQConstants.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Boolean isExists(String data, Integer type) {
        if (type!=1&&type!=2){
            throw new LyException(400,"参数类型错误，需要1或者2");
        }
        return query()
                .eq(type==1,"username",data)
                .eq(type==2,"phone",data)
                .count()==1;
    }

    @Override
    public void sendMessage(String phone) {
        //1、检查手机号码格式
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(400,"请求参数有误");
        }
        //2、生成6为随机的验证码
        String code = RandomStringUtils.randomNumeric(6);
        //3、将验证码存入reids中并设置过期时间
        redisTemplate.opsForValue().set(RedisConstants.SMS_PREFIX+phone,code,5, TimeUnit.MINUTES);
        //4、通过mq消息队列发送消息
        Map<String,String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        amqpTemplate.convertAndSend(ExchangeConstants.SMS_EXCHANGE_NAME,RoutingKeyConstants.VERIFY_CODE_KEY,map);
    }

    @Override
    public void register(User user, String code) {
        // 1.校验验证码
        // 1.1 取出redis中的验证码
        String cacheCode = redisTemplate.opsForValue().get(RedisConstants.SMS_PREFIX + user.getPhone());
        // 1.2 比较验证码
        if (!StringUtils.equals(code, cacheCode)) {
            throw new LyException(400, "验证码错误");
        }
        // 2.对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 3.写入数据库
        save(user);
    }

    @Override
    public UserDTO queryUserByPhoneAndPassword(String username, String password) {
        //根据用户名查询
        User user = getOne(new QueryWrapper<User>().eq("username", username));
        if (user==null){
            throw new LyException(400,"用户名不存在");
        }
        //校验密码
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400,"密码错误");
        }
        //返回数据
        return new UserDTO(user);
    }
}
